import { ref } from 'vue'
import { defineStore } from 'pinia'
import { Connector, ConnectorEvents, ProviderTypes } from '@/ethers-core'
import { toNumber } from '@/utils'

const connect: Connector = new Connector()
export const useConnectorStore = defineStore('address', () => {
  const account = ref('')
  const chainId = ref(0)
  async function initProvider(type: ProviderTypes) {
    await connect.initProvider(type)
    await connect.activate()
    localStorage.setItem('ProviderTypes', type)
  }
  connect.eventEmitter.on(ConnectorEvents.AccountsChanged, (accounts: any) => {
    if (accounts.length === 0) {
      disconnect()
    }
    account.value = accounts[0]
  })
  connect.eventEmitter.on(ConnectorEvents.ChainChanged, (cId: string) => {
    chainId.value = toNumber(String(cId))
  })

  function disconnect() {
    account.value = ''
    localStorage.removeItem('ProviderTypes')
  }

  return {
    account,
    chainId,
    initProvider,
    disconnect,
    connect,
  }
})
